<template>
  <div style="width: 100%">
    <el-input v-model="fileCusUrl" />
    <el-upload
      v-model:file-list="fileList"
      name="file"
      :action="uploadUrl"
      :headers="headers"
      :multiple="true"
      :data="params"
      :on-remove="handleChange"
      :on-success="handleChange"
      :limit="limit"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>
<script setup>
import { ref, onMounted, getCurrentInstance, watch } from "vue";

const { proxy } = getCurrentInstance();

const emits = defineEmits(["update:fileKey"]);

const props = defineProps({
  fileKey: {
    type: String,
    default: "",
  },
  limit: {
    type: Number,
    default: 9,
  },
});

const fileList = ref([]);

const uploadUrl = proxy.$comStore.app.baseApi + "/public/storage/store";

const fileCusUrl = ref("");

onMounted(() => {
  props.fileKey
    .split(",")
    .filter((item) => item)
    .forEach((item) => {
      fileList.value.push({
        name: item,
        response: {
          data: {
            fileKey: item,
          },
        },
      });
    });
});

watch(fileCusUrl, (newVal) => {
  emits("update:fileKey", newVal);
});

const handleChange = () => {
  let files = fileList.value.map((item) => item.response.data.fileKey);
  let url = "";
  if (props.limit > 1) {
    url = files.join(",");
  } else {
    url = files.length > 0 ? files[0] : "";
  }
  emits("update:fileKey", url);
  fileCusUrl.value = files.join(",");
};

const headers = {
  ntd_token: "ntd_fmhb",
};

const params = ref({
  channelBusinessId: "402809817fbc4f3d017fbcbed26a001d",
  bucketName: "app-bucket",
  fileKey: undefined,
});
</script>
